import React, { Component } from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'
import { Link } from 'react-router-dom'
import NavHeader from 'common/NavHeader'
import styles from './index.module.scss'
import { withFormik, Field, Form, ErrorMessage } from 'formik'
import http from 'utils/http'
import { setToken } from 'utils/token'
import * as yup from 'yup'

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/

class Login extends Component {
  render() {
    return (
      <div className={styles.login}>
        {/* 顶部导航 */}
        <NavHeader>账号登录</NavHeader>
        {/* 上下留白 */}
        <WhiteSpace size="xl" />
        <WingBlank>
          <Form>
            <div className="formItem">
              <Field
                className="input"
                name="username"
                placeholder="请输入账号"
              />
            </div>
            <ErrorMessage component="div" className="error" name="username" />

            <div className="formItem">
              <Field
                className="input"
                name="password"
                type="password"
                placeholder="请输入密码"
              />
            </div>
            <ErrorMessage component="div" className="error" name="password" />

            <div className="formSubmit">
              <button className="submit" type="submit">
                登 录
              </button>
            </div>
          </Form>
          <Flex className="backHome">
            <Flex.Item>
              <Link to="/register">还没有账号，去注册~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

const config = {
  // 准备表单数据
  mapPropsToValues: () => {
    return {
      username: '',
      password: '',
    }
  },
  // 处理表单提交
  handleSubmit: async (values, formikBag) => {
    const res = await http.post('/user/login', {
      username: values.username,
      password: values.password,
    })
    const { status, body } = res.data
    if (status === 200) {
      Toast.success('恭喜, 登录成功', 2, null, false)
      setToken(body.token)

      // 如果是从其他页面拦截过来的, 那么登录成功回到那一页
      const state = formikBag.props.location.state
      if (state) {
        // 登录过了, 这个登录页就不要了
        formikBag.props.history.replace(state.from.pathname)
      } else {
        // 返回上一页的情况, 登录页也不会加到浏览器历史记录中
        formikBag.props.history.go(-1)
      }
    } else {
      // 登录失败
      Toast.fail('用户名或者密码错误', 2, null, false)
      formikBag.resetForm()
    }
  },
  // 配置校验, 就算错误, 也只是将错误消息收集到 errors 对象中去了
  validationSchema: yup.object().shape({
    username: yup
      .string()
      .required('用户名不能为空')
      .matches(REG_UNAME, '用户名必须是5-8位的有效字符'),
    password: yup
      .string()
      .required('用户密码不能为空')
      .matches(REG_PWD, '用户密码必须是5-12位有效的字符'),
  }),
}
export default withFormik(config)(Login)
